package com.ambitor.ipro.util;

import java.security.MessageDigest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * copy skyencc写的类，未彻底清理，部分方法已用不到
 * 
 * @author skyencc@126.com
 * 
 */
public class SkyenccUtil {

	private static Logger log = Logger.getLogger(SkyenccUtil.class);

	private static final String noPictureUrl = "/img/no_pic.gif";

	public static String getNoPicUrl() {
		return noPictureUrl;
	}

	public static String strToGBK(String input) throws Exception {
		if (input == null) {
			return "";
		}
		return new String(input.getBytes("UTF-8"), "ISO-8859-1");
	}

	public static String unescapeHtml(String text) {
		if (StringUtils.isEmpty(text))
			return text;
		text = StringEscapeUtils.unescapeHtml(text);
		StringBuilder sb = new StringBuilder();
		for (char c : text.toCharArray()) {
			if (c == 160 || c == 8194 || c == 8195)
				sb.append(" ");
			else
				sb.append(c);
		}
		return sb.toString();
	}

	public static String getUuidString() {
		return UUID.randomUUID().toString();
	}

	public static String numTransStr(int num) {
		int numTmp = num % 24;
		return ((numTmp < 10) ? "0" : "") + String.valueOf(numTmp) + ":00";
	}

	public static boolean validateSign(String sign, Map<String, String> params,
			String secret) throws Exception {
		boolean flag = false;
		if (sign != null && params != null && secret != null
				&& sign.equals(Signature(params, secret))) {
			flag = true;
		}
		return flag;
	}

	public static String Signature(Map<String, String> params, String secret)
			throws Exception {
		String result = "";
		try {
			String top_appkey = params.get("top_appkey");
			String top_parameters = params.get("top_parameters");
			String top_session = params.get("top_session");

			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] digest = md.digest((top_appkey + top_parameters
					+ top_session + secret).getBytes());
			BASE64Encoder encode = new BASE64Encoder();
			result = encode.encode(digest);
		} catch (Exception ex) {
			throw new Exception("Sign Error !");
		}

		return result;
	}

	public static Map<String, String> convertBase64StringtoMap(String str) {
		if (str == null)
			return null;

		BASE64Decoder decoder = new BASE64Decoder();
		String keyValues = null;

		try {
			keyValues = new String(decoder.decodeBuffer(str),"GB2312");
		} catch (Exception e) {
			log.error(str + "不是一个合法的BASE64编码字符串");
			return null;
		}

		if (keyValues == null || keyValues.length() <= 0)
			return null;

		String[] keyValueArray = keyValues.split("&");

		Map<String, String> params = new HashMap<String, String>();

		for (String keyValue : keyValueArray) {
			String[] param = keyValue.split("=");
			if (param == null || param.length != 2) {
				return null;
			}
			params.put(param[0], param[1]);
		}

		return params;
	}

	public static String getNextInstallDate(Date oldDate, int frequency) {
		Calendar c = Calendar.getInstance();
		c.setTime(oldDate); // 设置当前日期
		c.add(Calendar.DATE, frequency); // 日期加frequency天
		Date date = c.getTime();
		return formatDate(date);
	}

	public static String getPlanExecTime(Date today) {
		SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd 00:30:00");
		SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy-MM-dd 8:00:00");
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date startDate = fmt.parse(fmt1.format(today));
			Date endDate = fmt.parse(fmt2.format(today));
			return formatDate(randomDate(startDate, endDate));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return fmt1.format(today);
	}

	public static Date randomDate(Date startDate, Date endDate) {
		long millsecs = 0;
		if (startDate.getTime() >= endDate.getTime()) {
			millsecs = random(endDate.getTime(), startDate.getTime());
		} else {
			millsecs = random(startDate.getTime(), endDate.getTime());
		}
		return new Date(millsecs);
	}

	private static long random(long begin, long end) {
		long rtn = begin + (long) (Math.random() * (end - begin));
		return rtn;
	}

	public static String formatDate(Date date) {
		if (date == null)
			return StringUtils.EMPTY;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}

	public static String formatDate(long date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date(date));
	}

	public static String formatDateOfDayStart(Date date) {
		if (date == null)
			return StringUtils.EMPTY;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:01");
		return sdf.format(date);
	}

	public static Date getDateOfDayStart() {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd 00:00:01");
		Calendar c = Calendar.getInstance();
		c.setTime(Timestamp.valueOf(fmt.format(System.currentTimeMillis())));
		return c.getTime();
	}

	public static String formatDateOfDayStart(long date) {
		return formatDateOfDayStart(new Date(date));
	}

	public static String format2YMD(Date date) {
		if (date == null)
			return StringUtils.EMPTY;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	public static String format2YMDWithoutSeperator(Date date) {
		if (date == null)
			return StringUtils.EMPTY;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.format(date);
	}

	public static String formatDateCH(Date date) {
		if (date == null)
			return StringUtils.EMPTY;
		SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
		return sdf.format(date);
	}

	public static String formatDateCH(long date) {
		SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
		return sdf.format(date);
	}

	public static String format2YMDHOCLK(long date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
		return sdf.format(date);
	}

	public static String format2HMS(long duration) {
		long ms = duration % 1000;
		long s = duration / 1000;
		long m = s / 60;
		s = s % 60;
		long h = m / 60;
		m = m % 60;
		return h + "小时" + m + "分钟" + s + "秒" + ms + "毫秒";
	}

	public static long hours(long duration) {
		return duration / 1000 / 3600 / 24;
	}

	public static boolean isEmpty(String s) {
		if (s == null || "".equals(s))
			return true;
		else
			return false;
	}

	public static boolean isExpired(Timestamp deadline) {
		if (deadline == null)
			return false;
		Calendar c = Calendar.getInstance();
		c.setTime(Timestamp.valueOf(formatDateOfDayStart(System
				.currentTimeMillis())));
		c.add(Calendar.DATE, -2);
		deadline = Timestamp.valueOf(formatDateOfDayStart(deadline.getTime()));
		Date expireTime = c.getTime();
		return expireTime.after(deadline);
	}

	public static String parse2string(Object o) {
		return o == null ? "" : StringUtils.trimToEmpty(o.toString());
	}

	public static Map<String, Integer> parse(String settings, int total) {
		// 6_1:0,6_2:0,6_3:0,6_4:0,6_5:0,6_6:0,6_7:0#
		String[] settingArray = settings.split("#");
		Map<String, Integer> ratioMap = new HashMap<String, Integer>();

		for (String ds : settingArray) {
			String[] hsArray = ds.split(",");
			for (String hs : hsArray) {
				String[] st = hs.split(":");
				Float ratio = Float.valueOf(0.0f);
				if ((st.length == 2) && (st[1] != null)) {
					if (!st[1].matches("\\d+(\\.\\d+)?"))
						st[1] = "0.0";
					ratio = Float.valueOf(st[1]);
					ratioMap.put(st[0], Integer.valueOf((int) Math.floor(ratio
							* total / 100)));
				} else if (st.length == 1) {
					ratioMap.put(st[0], Integer.valueOf(0));
				}
			}
		}

		return ratioMap;
	}

	public static Calendar parse2DayOfYear(Calendar currentDate, int dayOfWeek,
			int hourOfDay, int minuteInHour) {
		int todayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK) - 1;
		if (todayOfWeek == 0)
			todayOfWeek = 7;
		currentDate.add(Calendar.DATE, (dayOfWeek + 7 - todayOfWeek) % 7);
		currentDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
		currentDate.set(Calendar.MINUTE, minuteInHour);
		currentDate.set(Calendar.SECOND, 0);
		currentDate.set(Calendar.MILLISECOND, 0);
		return currentDate;
	}

	public static void main(String[] args) {
		System.out.println(SkyenccUtil.unescapeHtml(null));
	}

}
